package com.seecoder.BlueWhale.controller;

import com.seecoder.BlueWhale.enums.CouponStatusEnum;
import com.seecoder.BlueWhale.enums.OrderStatusEnum;
import com.seecoder.BlueWhale.po.Coupon;
import com.seecoder.BlueWhale.po.Order;
import com.seecoder.BlueWhale.repository.CouponRepository;
import com.seecoder.BlueWhale.repository.OrderRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/ali")
@Slf4j
public class AliPayController {
    @Autowired
    OrderRepository orderRepository;

    @Autowired
    CouponRepository couponRepository;

    @PostMapping("/notify")
    public void notify(HttpServletRequest httpServletRequest){
        if (httpServletRequest.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            log.warn("=========支付宝异步回调========");
            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = httpServletRequest.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, httpServletRequest.getParameter(name));
            }
            String tradeName = params.get("out_trade_no");
            Integer[] id= Arrays.stream(tradeName.split("_")).map(Integer::parseInt).toArray(Integer[]::new);
            if(id.length>1){
                for (int i = 1; i < id.length; i++) {
                    Coupon coupon = couponRepository.findById(id[i].intValue());
                    coupon.setCouponStatus(CouponStatusEnum.USED);
                    couponRepository.save(coupon);
                }
            }
            Order order = orderRepository.findById(id[0].intValue());
            order.setStatus(OrderStatusEnum.UNSEND);
            orderRepository.save(order);
        }
    }

}
